package com.etoak.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.enums.ResultEnum;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.properties.ImageProperties;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> uploadImage(MultipartFile image) {
        if(ObjectUtils.isEmpty(image) || image.isEmpty()){
            return ResultVO.failed(ResultEnum.FILE_NULL_ERROR);
        }
        if(!imageProperties.getTypes().contains(image.getContentType())){
            String message = imageProperties.getTypes().stream().map(x -> x.substring(x.indexOf("/") + 1))
                    .collect(Collectors.joining("、"));
            return ResultVO.failed(ResultEnum.SUCCESS.getCode(),"上传类型必须其中类型之一：" + message);
        }

        String originalFilename = image.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + suffix;

        File uploadDir = new File(imageProperties.getLocation());
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        File destFile = new File(uploadDir,fileName);
        try {
            image.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = imageProperties.getPrefix().endsWith("/")
                ?imageProperties.getPrefix() + fileName
                :imageProperties.getPrefix() + "/" + fileName;
        return ResultVO.success(path);
    }


}
